
package com.starshineworks.util;

import com.starshineworks.entities.EntityE;

import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import org.codehaus.jackson.map.*;

public class ObjectBuilder {

    private MenuManager mgr = null;

    private MenuManager getMenuManager() {
        if (mgr == null) {
            mgr = new MenuManager();
        }
        return mgr;
    } 
            
    public String buildMenu(Integer              menuid, 
                            Integer              rowId, 
                            Map<String,String[]> mp) {
        String y = "";
        Menu m = getMenuManager().createRequestMenu(menuid, rowId, mp);
        if (m != null) {
            y = m.toHTML(rowId);
        }
        return y;
    }

    public String buildList(String             type, 
                            int                view) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        String none = "FUNCTION NOT IMPLEMENTED";
        List<Object> desc = new ArrayList<Object>();
        desc.add(none);
        String pkg = EntityE.packageName();
        try {
            Class cls = Class.forName(pkg+"."+type);
            List<EntityE> list = EntityE.retrieve(cls.newInstance());
            if (list != null) {
                if (!list.isEmpty()) {
                    desc.clear();
                    for (EntityE ent: list) {
                        ent.refreshDisplay(view);
                        desc.add(ent);
                    }
                }
            }
        }
        catch (Exception e) {
            Util.handleException(e);
        }
        String str = "";
        try {
            str = mapper.writeValueAsString(desc);
        } catch (Exception e) {
            Util.handleException(e);
        }
        return str;
    }
    
}
